package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WQbdXhdhService;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;

import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.GlobalTypeService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.qbdms.model.WQbdUnderqualiTrial;
import com.ccp.dev.qbdms.service.WQbdUnderqualiTrialService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;

import java.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.util.BaseUtil;

/**
 * 不合格品审理 信息操作处理控制器
 * 
 * @author prh
 * @date 2020-10-12 10:22:29
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "不合格品审理")
@RequestMapping("/qbdms/wQbdUnderqualiTrial")
public class WQbdUnderqualiTrialController extends SysBaseController{
    @Resource
    private WQbdUnderqualiTrialService wQbdUnderqualiTrialService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private WQbdXhdhService wQbdXhdhService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private GlobalTypeService globalTypeService;
    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: prh
     * @date: 2020-10-12 10:22:29
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到不合格品审理首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());

        //审理级别
        setDicToModelMap("sljb", modelMap);
        //审理结论
        setDicToModelMap("sljlq", modelMap);
        //流程状态
        setDicToModelMap("lczt", modelMap);

        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));
        return "wQbdUnderqualiTrial/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询不合格品审理",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            // 没有排序,默认按照课题评审会会议时间倒序排列,课题评审会会议时间相同的情况下按创建时间倒序排列
            queryFilter.addFilter("orderField", "trialtime");
            queryFilter.addFilter("orderSeq", "desc");
        }
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdUnderqualiTrial> pageDatas = wQbdUnderqualiTrialService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        //TODO 添加编辑按钮权限控制
//        ZhiLiangConst.isDataAllowEdit(pageDatas, false);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }

    private void setDicToModelMap(String key, ModelMap modelMap) {
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey(key, false);
        modelMap.put(key + "List", JSON.toJSONString(dicList));
    }

    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: prh
     * @date: 2020-10-12 10:22:29
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到不合格品审理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);

        List<SysOrg> listOrg = new ArrayList<SysOrg>();
        listOrg = sysOrgService.queryAll();
        modelMap.put("researchRoomList", JSON.toJSONString(listOrg));

        if (StringUtil.isEmpty(id)) {
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            SysOrg sysOrg = (SysOrg) ContextUtil.getCurrentOrg();
            modelMap.put("filldept", sysOrg.getOrgName());
            modelMap.put("fillman", sysUser.getFullName());
            modelMap.put("filldate", TimeUtil.getCurrentDate());
            modelMap.put("fillmanaccount", sysUser.getAccount());
            modelMap.put("filldeptid", sysOrg.getCode());
            modelMap.put("fillmanid", sysUser.getUserId());
        }
        String userId = ContextUtil.getCurrentUserId();
        SysOrg org = sysOrgService.getOrgByUserId(userId);
        modelMap.put("dept", org.getCode());
        modelMap.put("deptname", org.getOrgName());
        if (StringUtil.isEmpty(id)) {
            //编号
            String numb =wQbdUnderqualiTrialService.generateNewRegisternum();
            modelMap.put("numb", numb);
            modelMap.put("num", wQbdUnderqualiTrialService.generateNewRegisternumS(numb));
        }
        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));

        //审理级别
        setDicToModelMap("sljb", modelMap);
        setDicToModelMap("lczt", modelMap);

        setDicToModelMap("cplb", modelMap);
        GlobalType zsfl1 = globalTypeService.getByDictNodeKey("cplb");
        modelMap.put("typeId", zsfl1.getTypeId());

        return "wQbdUnderqualiTrial/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdUnderqualiTrial 保存的对象
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存不合格品审理数据",detail="<#if isAdd>新增<#else>编辑</#if>不合格品审理数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>成功></#if>")
    public Object save(@RequestBody WQbdUnderqualiTrial wQbdUnderqualiTrial) {
        String id = wQbdUnderqualiTrial.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdUnderqualiTrial.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdUnderqualiTrial);

            wQbdUnderqualiTrial.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdUnderqualiTrial.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdUnderqualiTrial.setCreateTime(new Date());

            result = wQbdUnderqualiTrialService.add(wQbdUnderqualiTrial);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdUnderqualiTrial);

            wQbdUnderqualiTrial.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdUnderqualiTrial.setUpdateTime(new Date());

            result = wQbdUnderqualiTrialService.update(wQbdUnderqualiTrial);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdUnderqualiTrialService.getOneById(id), wQbdUnderqualiTrial));
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到不合格品审理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        return "wQbdUnderqualiTrial/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询不合格品审理的一条数据",detail="根据主键id查询不合格品审理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdUnderqualiTrial wQbdUnderqualiTrial = wQbdUnderqualiTrialService.getOneById(id);
        if (null == wQbdUnderqualiTrial) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdUnderqualiTrial);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除不合格品审理数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdUnderqualiTrial wQbdUnderqualiTrial = wQbdUnderqualiTrialService.getOneById(key);
            if (!userId.equals(wQbdUnderqualiTrial.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdUnderqualiTrialService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导出选择字段页面
    *
    * @param: [request] http请求
    * @param: modelMap
    * @return: java.lang.String
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    * @throws Exception
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到不合格品审理导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdUnderqualiTrial.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出不合格品审理数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: prh
    * @date: 2020-10-12 10:22:29
    */
    @RequestMapping("/exportData")
    @Action(description="导出不合格品审理数据信息",detail="导出不合格品审理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdUnderqualiTrial> list = this.wQbdUnderqualiTrialService.queryAll(queryFilter);
        if (list.isEmpty()) {
            list.add(new WQbdUnderqualiTrial());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, list, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

}
